<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class wechat extends a_base {

    public $classpropertyid = 2;

    public function __construct() {
        parent::__construct();
        $this->load->model('m_wechat');
        $this->load->model('m_weixin');
    }

    /*微信App配置*/
    public function config(){
        $data['info'] = $this->m_public->getRowInfo('weixinconfig');
        $this->load->view('wechat/config', $data);
    }

    public function config_action(){
        $info = $this->input->post();
        $old_config = $this->m_public->getRowInfo('weixinconfig');
        if(!empty($old_config)){
            $this->m_public->editInfo(array('id'=>$old_config['id']),$info,'weixinconfig');
        }else{
            $this->m_public->addRowInfo('weixinconfig',$info);
        }
        redirect('wechat/config');
    }

    /*自定义菜单*/
    public function menu(){
        $condition['where'] = array('menu_parent'=>0);
        $data['info'] = $this->m_wechat->get_data_list('weixinmenu',$condition);
        foreach($data['info'] as $key=>$val){
            $condition1['where'] = array('menu_parent'=>$val['menu_id']);
            $data['info'][$key]['son'] = $this->m_wechat->get_data_list('weixinmenu',$condition1);
        }
        $this->load->view('wechat/menu', $data);
    }

    public function menu_add($menu_id){
        if($menu_id){
            $data['info'] = $this->m_public->getRowInfo('weixinmenu',array('menu_id'=>$menu_id));
        }
        $this->load->view('wechat/menu_add', $data);
    }

    public function menu_action($menu_id=''){
        $info = $this->input->post();
        if($menu_id){
            $check_key_menu = $this->m_public->getRowInfo('weixinmenu',array('menu_key'=>$info['KeyValue']));
            $check_key_msg = $this->m_public->getRowInfo('weixinmsgreply',array('KeyValue'=>$info['KeyValue']));
            if(!empty($check_key_msg) || (!empty($check_key_menu) && $check_key_menu['menu_id'] != $menu_id)){
                echo '已存在相同的key值,<a href="javascript:window.history.back(-1);">点此返回</a>';exit;
            }
            $this->m_public->editInfo(array('menu_id'=>$menu_id),$info,'weixinmenu');
        }else{
            if(!empty($info)){
                $check_key_menu = $this->m_public->getRowInfo('weixinmenu',array('menu_key'=>$info['KeyValue']));
                $check_key_msg = $this->m_public->getRowInfo('weixinmsgreply',array('KeyValue'=>$info['KeyValue']));
                if(!empty($check_key_menu) || !empty($check_key_msg)){
                    echo '已存在相同的key值,<a href="javascript:window.history.back(-1);">点此返回</a>';exit;
                }
                $this->m_public->addRowInfo('weixinmenu',$info);
            }
        }
        redirect('wechat/menu');
    }

    public function menu_add_son($menu_id){
        $data['menu_id'] = $menu_id;
        $this->load->view('wechat/menu_add_son', $data);
    }

    public function menu_add_son_action($menu_id){
        $info = $this->input->post();
        $this->m_public->addRowInfo('weixinmenu',$info);
        redirect('wechat/menu');
    }

    public function menu_synoc(){
        $menus = array();
        $first = $this->m_public->getAllInfo('weixinmenu', array('menu_parent'=>0));
        foreach($first as $key => $val){
            $second = $this->m_public->getAllInfo('weixinmenu', array('menu_parent'=>$val['menu_id']));
            if(empty($second)){
                switch ($val['menu_action']) {
                    case 'view':
                        $list1['type'] = 'view';
                        $list1['name'] = $val['menu_title'];
                        $list1['url'] = $val['menu_url'];
                        break;

                    case 'click':
                        $list1['type'] = 'click';
                        $list1['name'] = $val['menu_title'];
                        $list1['key'] = $val['menu_key'];
                        break;

                    default:
                        # code...
                        break;
                }
                $menus['button'][$key] = $list1;
                unset($list1);
            }else{
                $list2['name'] = $val['menu_title'];
                foreach($second as $k => $v){
                    switch ($v['menu_action']) {
                        case 'view':
                            $list2['sub_button'][$k]['type'] = 'view';
                            $list2['sub_button'][$k]['name'] = $v['menu_title'];
                            $list2['sub_button'][$k]['url'] = $v['menu_url'];
                            break;

                        case 'click':
                            $list2['sub_button'][$k]['type'] = 'click';
                            $list2['sub_button'][$k]['name'] = $v['menu_title'];
                            $list2['sub_button'][$k]['key'] = $v['menu_key'];
                            break;

                        default:
                            # code...
                            break;
                    }
                }
                $menus['button'][$key] = $list2;
                unset($list2);
            }
        }

        /*查询，不为空删除*/
        $old_menu = $this->m_weixin->synoc_weixin('',array('menu','get'));
        if(!empty($old_menu)){
            $this->m_weixin->synoc_weixin('',array('menu','delete'));
        }
        $intertype = array('menu','create');
        $menus_str = $this->json_encode($menus);
        $re = $this->m_weixin->synoc_weixin($menus_str,$intertype);
        if($re === false){
            echo '同步失败';
        }else{
            if($re['errcode'] != '0'){
                if($re['errcode'] == 40001){
                    $token_data = array('access_token'=>'');
                    $this->session->set_userdata($token_data);
                }
                echo '同步失败:'.$re['errcode'].$re['errmsg'].',请重试';
            }else{
                echo '同步成功:'.$re['errmsg'];
            }
        }
    }

    /*微信消息*/
    public function msg(){
        $ToUserName = $this->input->post('ToUserName');
        $condition['where'] = array();
        if($ToUserName != false){
            $condition['where'] = array(
                'ToUserName' => $ToUserName
            );
        }

        $cnt = $this->m_wechat->get_count('weixinmsg',$condition['where']);
        $page = $this->input->get('page'); //当前页
        $page = intval($page);
        if ($page < 1) {
            $page = 1;
        }
        $page_size = 10;
        $arr = array(
            'page' => $page, //当前页
            'page_size' => $page_size, //分页总大小
            'total' => $cnt//总记录数
        );
        $start_page = ($page - 1) * $page_size;

        $condition['limit'] = $page_size;
        $condition['offset'] = $start_page;
        $data['pagination'] = new pagination($arr);
        $data['list'] = $this->m_wechat->get_data_list('weixinmsg',$condition);

        $this->load->view('wechat/msg', $data);
    }

    /*微信分组*/
    public function group(){
        $groupname = $this->input->post('groupname');
        $condition['where'] = array();
        if($groupname != false){
            $condition['where'] = array(
                'groupname' => $groupname
            );
        }

        $cnt = $this->m_wechat->get_count('weixingroup',$condition['where']);
        $page = $this->input->get('page'); //当前页
        $page = intval($page);
        if ($page < 1) {
            $page = 1;
        }
        $page_size = 10;
        $arr = array(
            'page' => $page, //当前页
            'page_size' => $page_size, //分页总大小
            'total' => $cnt//总记录数
        );
        $start_page = ($page - 1) * $page_size;

        $condition['limit'] = $page_size;
        $condition['offset'] = $start_page;
        $data['pagination'] = new pagination($arr);
        $data['info'] = $this->m_wechat->get_data_list('weixingroup',$condition);

        $this->load->view('wechat/group', $data);
    }

    public function group_add($groupid){
        if($groupid){
            $data['info'] = $this->m_public->getRowInfo('weixingroup',array('groupid'=>$groupid));
        }else{
            $data['info'] = "";
        }
        $this->load->view('wechat/group_add',$data);
    }

    public function group_action($groupid=''){
        $info = $this->input->post();
        if($groupid){
            $check_groupname = $this->m_public->getRowInfo('weixingroup',array('groupname'=>$info['groupname']));
            if(!empty($check_groupname) && $check_groupname['groupid'] != $groupid){
                echo '已存在相同的分组名,<a href="javascript:window.history.back(-1);">点此返回</a>';exit;
            }
            /*同步微信*/
            $synoc_data['group'] = array(
                'id'=>$groupid,
                'name'=>$info['groupname']
            );
            $synoc_data_str = $this->json_encode($synoc_data);
            $intertype = array('groups','update');
            $re = $this->m_weixin->synoc_weixin($synoc_data_str,$intertype);
            if($re === false){
                echo '同步至微信失败';
            }else{
                if($re['errcode'] != 0){
                    echo '同步至微信失败:'.$re['errcode'].$re['errmsg'];
                }else{
                    $this->m_public->editInfo(array('groupid'=>$groupid),$info,'weixingroup');
                }
            }
        }else{
            if(!empty($info)){
                $check_groupname = $this->m_public->getRowInfo('weixingroup',array('groupname'=>$info['groupname']));
                if(!empty($check_groupname)){
                    echo '已存在相同的分组名,<a href="javascript:window.history.back(-1);">点此返回</a>';exit;
                }
                $info['childnum'] = 0;
                /*同步至微信*/
                $synoc_data['group'] = array('name'=>$info['groupname']);
                $synoc_data_str = $this->json_encode($synoc_data);
                $intertype = array('groups','create');
                $re = $this->m_weixin->synoc_weixin($synoc_data_str,$intertype);
                if($re === false){
                    echo '同步至微信失败';
                }else{
                    if(isset($re['errcode'])){
                        echo '同步至微信失败:'.$re['errcode'].$re['errmsg'];
                    }else{
                        $info['groupid'] = $re['group']['id'];

                        $this->m_public->addRowInfo('weixingroup',$info);
                    }
                }
            }
        }
        redirect('wechat/group');
    }

    public function group_synoc(){
        $intertype = array('groups','get');
        $re = $this->m_weixin->synoc_weixin('',$intertype);
        if($re['errcode'] != 0){
            if($re['errcode'] == 40001){
                $token_data = array('access_token'=>'');
                $this->session->set_userdata($token_data);
            }
            echo '同步失败:'.$re['errcode'].$re['errmsg'].'，请重试';exit;
        }else{
            $all_data = $this->m_public->getAllInfo('weixingroup');
            foreach($all_data as $key=>$val){
                $this->m_public->delInfo('weixingroup',array('groupid'=>$val['groupid']));
            }

            foreach($re['groups'] as $key=>$val){
                $info['groupid'] = $val['id'];
                $info['groupname'] = $val['name'];
                $info['childnum'] = $val['count'];
                $this->m_public->addRowInfo('weixingroup',$info);
            }
        }
        echo '同步成功！';exit;
    }

    /*微信用户*/
    public function member(){
        $data['group'] = $this->m_wechat->get_data_list('weixingroup');

        $cnt = $this->m_wechat->get_count('weixinuser',array());
        $page = $this->input->get('page'); //当前页
        $page = intval($page);
        if ($page < 1) {
            $page = 1;
        }
        $page_size = 10;
        $arr = array(
            'page' => $page, //当前页
            'page_size' => $page_size, //分页总大小
            'total' => $cnt//总记录数
        );
        $start_page = ($page - 1) * $page_size;

        $data['pagination'] = new pagination($arr);
        $data['member'] = $this->m_wechat->get_data_multi(array(),$page_size,$start_page);

        $this->load->view('wechat/member', $data);
    }

    /*同步用户*/
    public function member_synoc(){

        $intertype = array('user','get');
        $re = $this->m_weixin->synoc_weixin('',$intertype);
        if(isset($re['errcode'])){
            if($re['errcode'] == 40001){
                $token_data = array('access_token'=>'');
                $this->session->set_userdata($token_data);
            }
            echo '同步失败:'.$re['errcode'].$re['errmsg'].'，请重试';exit;
        }else{
            foreach($re['data']['openid'] as $key=>$val){
                $info['openid'] = $val;
                $old_info = $this->m_public->getRowInfo('weixinuser',array('openid'=>$val));
                if(empty($old_info)){
                    $this->m_public->addRowInfo('weixinuser',$info);
                }
            }
        }
        echo '同步成功！';exit;
    }

    /*设置备注名*/
    public function setmemo(){
        $userId = $this->input->post('userId');
        $data['nickname'] = $this->input->post('memo');
        $oldInfo = $this->m_public->getRowInfo('weixinuser',array('weixinUserID'=>$userId));
        $openId = $oldInfo['openid'];
        $intertype = array('user','info','updateremark');
        $synoc_data = array(
            'openid'=>$openId,
            'remark'=>$data['nickname']
        );
        $synoc_data = $this->json_encode($synoc_data);
        $re = $this->m_weixin->synoc_weixin($synoc_data,$intertype);
        if($re['errcode'] != 0){
            if($re['errcode'] == 40001){
                $token_data = array('access_token'=>'');
                $this->session->set_userdata($token_data);
            }
            echo '同步失败:'.$re['errcode'].$re['errmsg'].'，请重试';exit;
        }else{
            $this->m_public->editInfo(array('weixinUserID'=>$userId),$data,'weixinuser');
        }

        redirect('wechat/member');
    }

    /*移动分组*/
    public function move_group(){
        $id = $this->input->post('id');
        $new_group = $this->input->post('new_group');
        $idArr = explode(',',$id);
        if(count($idArr) > 1){
            $nums = count($idArr) - 1;
            foreach($idArr as $key=>$val){
                if($key != 0){
                    $oldInfo = $this->m_public->getRowInfo('weixinuser',array('weixinUserID'=>$val));
                    if($oldInfo['groupid'] == ''){
                        $oldInfo['groupid'] = 0;
                    }
                    $openId = $oldInfo['openid'];
                    $intertype = array('groups','members','update');
                    $synoc_data = array(
                        'openid'=>$openId,
                        'to_groupid'=>$new_group
                    );
                    $synoc_data = $this->json_encode($synoc_data);
                    $re = $this->m_weixin->synoc_weixin($synoc_data,$intertype);

                    if($re['errcode'] != 0){
                        if($re['errcode'] == 40001){
                            $token_data = array('access_token'=>'');
                            $this->session->set_userdata($token_data);
                        }
                        echo '同步失败:'.$re['errcode'].$re['errmsg'].'，请重试';exit;
                    }else{
                        $old_group_info = $this->m_public->getRowInfo('weixingroup',array('groupid'=>$oldInfo['groupid']));
                        $new_group_info = $this->m_public->getRowInfo('weixingroup',array('groupid'=>$new_group));
                        $old_group_info['childnum'] -= $nums;
                        $new_group_info['childnum'] += $nums;

                        $this->m_public->editInfo(array('groupid'=>$oldInfo['groupid']),$old_group_info,'weixingroup');
                        $this->m_public->editInfo(array('groupid'=>$new_group),$new_group_info,'weixingroup');
                        $this->m_public->editInfo(array('weixinUserID'=>$val),array('groupid'=>$new_group),'weixinuser');
                    }
                }
            }
        }

    }

    /*微信回复消息设置*/
    public function remsg(){
        $MsgReplyWay = $this->input->post('MsgReplyWay');
        $MsgType = $this->input->post('MsgType');
        $condition['where'] = array();
        if($MsgReplyWay != false){
            $condition['where'] = array(
                'MsgReplyWay' => $MsgReplyWay
            );
        }
        if($MsgType != false){
            $condition['where'] = array(
                'MsgType' => $MsgType
            );
        }

        $cnt = $this->m_wechat->get_count('weixinmsgreply',$condition['where']);
        $page = $this->input->get('page'); //当前页
        $page = intval($page);
        if ($page < 1) {
            $page = 1;
        }
        $page_size = 10;
        $arr = array(
            'page' => $page, //当前页
            'page_size' => $page_size, //分页总大小
            'total' => $cnt//总记录数
        );
        $start_page = ($page - 1) * $page_size;

        $condition['limit'] = $page_size;
        $condition['offset'] = $start_page;
        $data['pagination'] = new pagination($arr);
        $data['info'] = $this->m_wechat->get_msgreply($condition['where'],$page_size,$start_page);

        $this->load->view('wechat/remsg',$data);
    }

    public function remsg_add($weixinMsgReplyID){
        if($weixinMsgReplyID){
            $data['info'] = $this->m_public->getRowInfo('weixinmsgreply',array('weixinMsgReplyID'=>$weixinMsgReplyID));
        }else{
            $data['info'] = '';
        }
        $this->load->view('wechat/remsg_add',$data);
    }

    public function remsg_action($weixinMsgReplyID){
        $info = $this->input->post();
        if($weixinMsgReplyID){
            $check_key_menu = $this->m_public->getRowInfo('weixinmenu',array('menu_key'=>$info['KeyValue']));
            $check_key_msg = $this->m_public->getRowInfo('weixinmsgreply',array('KeyValue'=>$info['KeyValue']));
            if(!empty($check_key_menu) || (!empty($check_key_msg) && $check_key_msg['weixinMsgReplyID'] != $weixinMsgReplyID)){
                echo '已存在相同的key值,<a href="javascript:window.history.back(-1);">点此返回</a>';exit;
            }
            $this->m_public->editInfo(array('weixinMsgReplyID'=>$weixinMsgReplyID),$info,'weixinmsgreply');
        }else{
            if(!empty($info)){
                $check_key_menu = $this->m_public->getRowInfo('weixinmenu',array('menu_key'=>$info['KeyValue']));
                $check_key_msg = $this->m_public->getRowInfo('weixinmsgreply',array('KeyValue'=>$info['KeyValue']));
                if(!empty($check_key_msg) || !empty($check_key_menu)){
                    echo '已存在相同的key值,<a href="javascript:window.history.back(-1);">点此返回</a>';exit;
                }
                $info['AdminID'] = $this->session->userdata['user_id'];
                $info['CreateTime'] = date('Y-m-d H:i:s',time());
                $this->m_public->addRowInfo('weixinmsgreply',$info);
            }
        }
        redirect('wechat/remsg');
    }

    /*微信群发*/
    public function sendmore(){
        $condition['where'] = array();

        $cnt = $this->m_wechat->get_count('weixinmore',$condition['where']);
        $page = $this->input->get('page'); //当前页
        $page = intval($page);
        if ($page < 1) {
            $page = 1;
        }
        $page_size = 10;
        $arr = array(
            'page' => $page, //当前页
            'page_size' => $page_size, //分页总大小
            'total' => $cnt//总记录数
        );
        $start_page = ($page - 1) * $page_size;

        $condition['limit'] = $page_size;
        $condition['offset'] = $start_page;
        $data['pagination'] = new pagination($arr);
        $data['info'] = $this->m_wechat->get_data_list('weixinmore',$condition);

        $this->load->view('wechat/sendmore',$data);
    }

    public function more_add($msgid){
        if($msgid){
            $data['info'] = $this->m_public->getRowInfo('weixinmore',array('msgid'=>$msgid));
        }else{
            $data['info'] = '';
        }
        $this->load->view('wechat/more_add',$data);
    }

    public function more_action($msgid){
        $info = $this->input->post();
        if($msgid){
            $this->m_public->editInfo(array('msgid'=>$msgid),$info,'weixinmore');
        }else{
            if(!empty($info)){
                $info['msgtype'] = 'more';
                $info['add_time'] = date('Y-m-d H:i:s',time());
                $this->m_public->addRowInfo('weixinmore',$info);
            }
        }
        redirect('wechat/sendmore');
    }

    public function more_do_send($id){
        $msgInfo = $this->m_public->getRowInfo('weixinmore',array('msgid'=>$id));
        $users = $this->m_public->getAllInfo('weixinuser');
        $synoc_data['touser'] = array();
        foreach($users as $key=>$val){
            $synoc_data['touser'][] = $val['openid'];
        }
        $synoc_data['msgtype'] = 'text';
        $synoc_data['text'] = array('content'=>$msgInfo['msgcontent']);
        $intertype = array('message','mass','send');
        $synoc_data = $this->json_encode($synoc_data);
        $re = $this->m_weixin->synoc_weixin($synoc_data,$intertype);
        if($re['errcode'] != 0){
            echo '查询失败:'.$re['errcode'].$re['errmsg'];exit;
        }else{
            echo '发送成功:'.$re['errmsg'];
        }
    }

    /*多客服聊天信息*/
    public function service(){
        $start_time = $this->input->post('start_time');
        $end_time = $this->input->post('end_time');
        $start_time_get = $_GET['start_time'];
        $end_time_get = $_GET['end_time'];

        if(!$start_time && !$end_time && !$start_time_get && !$end_time_get){
            $data['info'] = array();
        }else if($start_time && $end_time){
            $data['start_time'] = $start_time;
            $data['end_time'] = $end_time;
        }else if($start_time_get && $end_time_get){
            $data['start_time'] = $start_time_get;
            $data['end_time'] = $end_time_get;
        }

        if($data['start_time'] && $data['end_time']){
            $page = $_GET['page'] == '' ? 1 : $_GET['page'];
            $synoc_data = array(
                'starttime' => strtotime($start_time),
                'endtime' => strtotime($end_time),
                'pagesize' => 10,
                'pageindex' => $page
            );
            $synoc_data = $this->json_encode($synoc_data);
            $intertype = array('customservice','getrecord');
            $re = $this->m_weixin->synoc_weixin_xml($synoc_data,$intertype);
            if(isset($re['errcode'])){
                echo '查询失败:'.$re['errcode'].$re['errmsg'];exit;
            }else{
                $data['info'] = $re['recordlist'];
                if(count($re['recordlist']) == 10){
                    $data['next_page'] = $page + 1;
                }
                if($page > 1){
                    $data['last_page'] = $page - 1;
                }
            }
        }

        $this->load->view('wechat/service', $data);
    }

    public function delete_info($url,$parmykey,$table,$ids)
    {
        if(!$ids){
            redirect("wechat/$url");
        }
        $idArr = explode('.', $ids);
        foreach($idArr as $k=>$v){
            if($url == 'menu'){
                $sons = $this->m_public->getAllInfo($table,array('menu_parent'=>$v),'menu_id');
                if(!empty($sons)){
                    foreach($sons as $key=>$val){
                        $this->m_public->delInfo($table,array($parmykey=>$val['menu_id']));
                    }
                }
            }
            $res = $this->m_public->delInfo($table,array($parmykey=>$v));
        }
        redirect("wechat/$url");
    }

    /*json数组，不转义汉字*/
    private function json_encode ($input) {

        // 从 PHP 5.4.0 起, 增加了这个选项.
        if(defined('JSON_UNESCAPED_UNICODE')){
            return json_encode($input, JSON_UNESCAPED_UNICODE);
        }
        if(is_string($input)){
            $text = $input;
            $text = str_replace('\\', '\\\\', $text);
            $text = str_replace(
                array("\r", "\n", "\t", "\""),
                array('\r', '\n', '\t', '\\"'),
                $text);
            return '"' . $text . '"';
        }else if(is_array($input) || is_object($input)){
            $arr = array();
            $is_obj = is_object($input) || (array_keys($input) !== range(0, count($input) - 1));
            foreach($input as $k=>$v){
                if($is_obj){
                    $arr[] = self::json_encode($k) . ':' . self::json_encode($v);
                }else{
                    $arr[] = self::json_encode($v);
                }
            }
            if($is_obj){
                return '{' . join(',', $arr) . '}';
            }else{
                return '[' . join(',', $arr) . ']';
            }
        }else{
            return $input . '';
        }

    }


}
